<?php
/**
 * Created by PhpStorm.
 * User: HuangLuSen
 * Date: 2017/5/11
 * Time: 11:29
 */

namespace app\common\traits;
use app\common\message\model\WechatZjsMessage;
use app\common\message\type\WechatTypeZjs;
use app\common\model\Wesmslog;
use EasyWeChat\Foundation\Application;
use app\common\message\type\WechatType;
use app\common\message\model\WechatMessage;
trait WechatZjs
{
//微信平台
    protected static $options=[
        /**
         * Debug 模式，bool 值：true/false
         *
         * 当值为 false 时，所有的日志都不会记录
         */
        'debug'  => true,
        /**
         * 账号基本信息，请从微信公众平台/开放平台获取
         */
        'app_id' => '',
        'secret' => '',
        'token'  => '',
        'aes_key' => '',
        'we_name'=>'',
        'we_id'=>'',
        'we_number'=>'',
        'we_type'=>1,
        /**
         * 日志配置
         *
         * level: 日志级别, 可选为：
         *         debug/info/notice/warning/error/critical/alert/emergency
         * permission：日志文件权限(可选)，默认为null（若为null值,monolog会取0644）
         * file：日志文件位置(绝对路径!!!)，要求可写权限
         */
        'log' => [
            'level'      => 'debug',
            'permission' => 0777,
            'file'       => '../runtime/log/easywechatzjs.log',
        ],
        /**
         * OAuth 配置
         *
         * scopes：公众平台（snsapi_userinfo / snsapi_base），开放平台：snsapi_login
         * callback：OAuth授权完成后的回调页地址
         */
        'oauth' => [
            'scopes'   => ['snsapi_userinfo'],
            'callback' => '/Zjs/login/receive.html',
        ],
        /**
         * 微信支付
         */
        'payment' => [
            'merchant_id'        => 'your-mch-id',
            'key'                => 'key-for-signature',
            'cert_path'          => 'E:/huangsen/cacert.pem', // XXX: 绝对路径！！！！
            'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！
            // 'device_info'     => '013467007045764',
            // 'sub_app_id'      => '',
            // 'sub_merchant_id' => '',
            // ...
        ],
        /**
         * Guzzle 全局设置
         *
         * 更多请参考： http://docs.guzzlephp.org/en/latest/request-options.html
         */
        'guzzle' => [
            'timeout' => 300.0, // 超时时间（秒）
            'verify' => false, // 关掉 SSL 认证（强烈不建议！！！）
        ],
    ];
    public static $wechatapp=null;
    //静态方法，单例统一访问入口
    static public function getInstance() {
        if (is_null ( self::$wechatapp ) || isset ( self::$wechatapp )) {
            $config=config('zjs.we_options');
            if(!empty($config)) self::$options=array_merge(self::$options,$config);
            self::$wechatapp = new Application(self::$options);
            config('app_debug',false);
            config('app_trace',false);
        }
        return self::$wechatapp;
    }
    /**
     * 检测微信是否为检测请求 并进行加密认证
     * @return bool
     */
    private function checkSignature()
    {
        $signature =input('signature');
        $timestamp = input('timestamp');
        $nonce = input('nonce');
        $config=config('zjs.we_options');
        if(!empty($config)) self::$options=array_merge(self::$options,$config);
        $token = self::$options['token'];
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 发送微信模板消息
     * @param $data
     */
    public function sendWechat($data){
        $wechattype = new WechatTypeZjs();
        $wechatmessage = new WechatZjsMessage($wechattype,$data);
        $wesmslog = new Wesmslog();
        $str = '';
        foreach ($data as $key=>$v){
            $str.=$key.":".$v.';';
        }
        $arr['send_id']     = $data['sendid'];
        $arr['receive_id']  = $data['userid'];
        $arr['order_id']    = $data['orderid'];
        $arr['send_msg']    = $str;
        $arr['log_type']    = 3;
        $array=false;
        try{
            $array = $wechatmessage->sendMessage();
        }catch (\Exception $exception){
            $arr['is_success']  = 2;
            $arr['error_msg']   ='用户id为'.$data['userid'].'的微信推送失败！错误信息是:'.$exception->getMessage().'，错误代码是:'.$exception->getCode();;
        }
        $wesmslog->save($arr);
        return $array;
    }
    public function traceHttp()
    {
        $this->logger("\n\nREMOTE_ADDR:".$_SERVER["REMOTE_ADDR"].(strstr($_SERVER["REMOTE_ADDR"],'101.226')? " FROM WeiXin": "Unknown IP"));
        $this->logger("QUERY_STRING:".$_SERVER["QUERY_STRING"]);
    }
    function logger($log_content)
    {
        $max_size = 500000;
        $log_filename = "log.html";
        if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
        file_put_contents($log_filename, date('Y-m-d H:i:s').$log_content."\r\n", FILE_APPEND);
    }
}